package service

import (
	"saas-app/app/dao"
	"saas-app/app/define"
	"saas-app/app/model"
	"strconv"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gtime"
)

type ClassMemberRepository interface {
	GetClassMemeberList(*define.ClassMemeberListParams) (list g.List, total int)
	CreateClassMember(member *model.ClassMember) uint
	LeaveClassMember(class_id, student_id, status uint) (id uint)
	IsExistClassMember(class_id, student_id uint) (uint, error)
	UpdateClassMember(id, status uint) bool
}

type classMember struct{}

func ClassMemberService() ClassMemberRepository {
	return &classMember{}
}

func (c classMember) GetClassMemeberList(params *define.ClassMemeberListParams) (list g.List, total int) {

	db := dao.ClassMember.Where("class_member.class_id = ?", params.ClassId)

	if params.Status != "0" && params.Status != "" {
		db = db.Where("class_member.status = ?", params.Status)
	}

	db = db.Where("class_member.deleted_at IS NULL").LeftJoin("student", "class_member.student_id = student.id")

	total, err := db.FindCount()

	if err != nil {
		panic(err)
	}

	if params.Page > 0 && params.Limit > 0 {
		db = db.Offset((params.Page - 1) * params.Limit).Limit(params.Limit)
	}

	result, err := db.All()

	if err != nil {
		panic(err)
	}

	return result.List(), total
}

func (c classMember) CreateClassMember(member *model.ClassMember) uint {

	if member.Status == "0" {
		member.Status = "1"
	}

	if member.EntryAt == nil {
		member.EntryAt = gtime.Now()
	}

	memberId, err := ClassMemberService().IsExistClassMember(uint(member.ClassId), uint(member.StudentId))
	if memberId != 0 || err != nil {
		panic("学员已存在")
	}

	if re, err := dao.ClassMember.Save(member); err != nil {
		panic(err)
	} else {
		id, err := re.LastInsertId()
		if err != nil {
			panic(err)
		}
		return uint(id)
	}

}

func (c classMember) LeaveClassMember(class_id, student_id, status uint) (id uint) {
	rowId, err := ClassMemberService().IsExistClassMember(class_id, student_id)
	if rowId == 0 || err != nil {
		panic("学员不存在")
	}
	idDelete := ClassMemberService().UpdateClassMember(rowId, status)
	if idDelete {
		return rowId
	}
	panic("删除失败")
}

func (c classMember) IsExistClassMember(class_id, student_id uint) (uint, error) {
	member, err := dao.ClassMember.Where("class_id = ?", class_id).Where("student_id = ?", student_id).And("status = 1").FindOne()
	if err != nil || member == nil {
		return 0, err
	}
	return uint(member.Map()["id"].(int)), nil
}

func (c classMember) UpdateClassMember(id, status uint) bool {

	db := dao.ClassMember.Where("id = ?", id)
	classMember := &model.ClassMember{}
	member, err := db.One()
	member.Struct(&classMember)
	if err != nil {
		return false
	}

	if status == 2 {
		classMember.LeaveAt = gtime.Now()
	}
	classMember.Status = strconv.Itoa(int(status))
	_, err = db.Update(classMember)
	return err == nil
}
